package com.fun_ordering.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fun_ordering.components.ApiResponse;
import com.fun_ordering.util.JJwtUtil;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置 HTTP 响应的内容类型为 JSON 格式，并指定字符编码为 UTF-8。
        response.setContentType("application/json;charset=utf-8");

        //1.token存入请求头中
        String token = request.getHeader("Token");
        //2.token的合法性 非空验证 合法验证
        //获取token
        //判断token是否正常
        if(StringUtils.isEmpty(token)){
            ApiResponse result = new ApiResponse();
            result.setCode(401l);
            result.setMsg("token失效");
            String json = new ObjectMapper().writeValueAsString(result);
            response.getWriter().print(json);
            //拦截
            return false;
        }

        //处理token是否有效
        //2.token的合法性 非空验证 合法验证
        boolean flag = JJwtUtil.checkToken(token);
        if(!flag){
            ApiResponse result = new ApiResponse();
            result.setCode(402l);
            result.setMsg("token不合法");
            String json = new ObjectMapper().writeValueAsString(result);
            response.getWriter().print(json);
            //拦截
            return false;
        }
        return true;
    }
}
